package com.example.myblog.controller;

import com.example.myblog.pojo.Article;
import com.example.myblog.pojo.User;
import com.example.myblog.service.ArticleService;
import com.example.myblog.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @BelongsProject: MyBlog
 * @BelongsPackage: com.example.myblog.controller
 * @ClassName LoginController
 * @CreateTime: 2025-05-28  23:03
 * @Author: TangLiFei
 */
@Controller
public class LoginController {
    @Autowired
    UserService userService;
    @Autowired
    private ArticleService articleService;

    @RequestMapping("/login")
    public String login(User user, HttpSession session){
        System.out.println("登录请求接收: " + user.getAccount() + "/" + user.getPwd());
        User user1=userService.findUserWithAuthorities(user);
        if (user1!=null){
            session.setAttribute("user",user1);
            System.out.println("登录成功，重定向到欢迎页");
            return "redirect:/welcome";
        }
        session.setAttribute("msg","账号或密码输入错误");
        System.out.println("登录失败");
        return "redirect:/";
    }

    @RequestMapping("/out")
    public String logout(HttpSession session){
        session.invalidate();
        return "redirect:/";
    }

  @RequestMapping("/welcome")
  public String welcome(Model model) {
      System.out.println("访问欢迎页面");
      List<Article> top6Articles = articleService.findTop6ArticlesByCommentCount();
      model.addAttribute("top6Articles", top6Articles);
      System.out.println("评论数最多的文章数据：" + top6Articles);
      return "welcome";
  }

}
